package com.wwj.core.wawa.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wwj.core.common.CodeConstants;
import com.wwj.core.wawa.entity.LogWaWaAdjust;
import com.wwj.core.wawa.entity.WaWa;
import com.wwj.core.wawa.entity.mapper.WawaMapper;
import com.wwj.core.wawa.service.IInventoryService;
import com.wwj.core.wawa.service.ILogWaWaAdjustService;
import com.wwj.framework.utils.ReturnData;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Auser on 2017/11/16.
 */
@Service
public class InventoryServiceImpl implements IInventoryService {

    @Resource
    private WawaMapper wawaMapper;

    @Resource
    private ILogWaWaAdjustService logWaWaAdjustService;


    @Override
    public Page<WaWa> findByPage(Map<String, Object> params, int offset, int limit) throws Exception {
        PageHelper.offsetPage(offset,limit);
        return (Page)wawaMapper.selectByPage(params);
    }

    @Override
    public ReturnData add(WaWa wawa) {
        String name = wawa.getName();
        if(null == name || "".equals(name)) return new ReturnData().failure("娃娃名称不能为空");
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("name",name);
        WaWa dbWaWa = wawaMapper.findByName(params);
        if(dbWaWa != null) return new ReturnData().failure("输入的娃娃名称已存在，请重新输入");
        WaWa lastWaWa = wawaMapper.findLastCode();
        if(null == lastWaWa){
            wawa.setCode(CodeConstants.INIT_WAWA_CODE);
        }else{
            wawa.setCode(lastWaWa.getCode()+1);
        }
        wawaMapper.addWaWa(wawa);
        return new ReturnData().success("添加娃娃成功");
    }

    @Override
    public void deleteById(Integer id) {
        wawaMapper.deleteById(id);
    }

    @Override
    public void updateIncoming(WaWa waWa) {
        wawaMapper.updateIncoming(waWa);
    }

    @Override
    public WaWa findById(Integer id) {
        return wawaMapper.findById(id);
    }

    @Override
    public void updateWaWa(WaWa waWa) throws Exception {
        wawaMapper.updateWaWa(waWa);
    }

    @Override
    public void addAdjustWaWa(LogWaWaAdjust logAdjust) throws Exception {
        WaWa waWa = new WaWa();
        waWa.setId(logAdjust.getWaWaId());
        waWa.setInventory(logAdjust.getAdjustAfter());
        wawaMapper.updateWaWa(waWa);
        logWaWaAdjustService.addLogWaWaAdjust(logAdjust);
    }
}
